<?php

require_once 'modules/question/models/Question.php';
require_once 'modules/content/models/ContentCategory.php';
require_once 'modules/language/models/Lang.php';
require_once 'modules/question/models/Unit.php';
require_once 'modules/question/models/Answer.php';
class question_AdminController extends Nine_Controller_Action_Admin 
{
    
    public function manageQuestionAction()
    {
    	$group = Nine_Registry::getLoggedInGroupId();
    	$this->view->group = $group;
    	
//    	echo "<pre>";print_r($group);die;
        $objQuestion = new Models_Question();
        $objLang    = new Models_Lang();
        $objCat     = new Models_ContentCategory();
        $objUnit = new Models_Unit();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_question', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Nine_Language::translate('manage Question '));
        $this->view->menu = array('question', 'managequestion');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        
//         echo "<pre>";print_r($data);die;
        
        
        
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->questionDisplayNum;
        } else {
            $this->session->questionDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->questionCondition;
        } else {
            $this->session->questionCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        /**
         * Get all categories
         */
        $this->view->allCats = $objCat->buildTree($objCat->getAllCategories(1,array('sorting ASC')));;
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('see_question', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
            }
        }
        
        /**
         * Get all questions
         */
        
        $allQuestion = $objQuestion->setAllLanguages(true)->getAllQuestions($condition, array('sorting ASC', 'question_gid DESC', 'question_id ASC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
//        echo '<pre>';print_r($allQuestion);die;
        /**
         * Count all questions
         */
        $count = count($objQuestion->setAllLanguages(true)->getAllQuestions($condition));
        /**
         * Format
         */
        $tmp    = array();
        $tmp2   = false;
        $tmpGid = @$allQuestion[0]['question_gid'];
        foreach ($allQuestion as $index=>$question) {
        	
        	$unit = $objUnit->getUnitById($question['level']);
        	$question['level_name'] = $unit['name'];
        	
        	
            /**
             * Change date
             */
            if (0 != $question['created_date']) {
                $question['created_date'] = date($config['dateFormat'], $question['created_date']);
            } else {
                $question['created_date'] = '';
            }
            if ($tmpGid != $question['question_gid']) {
                $tmp[]  = $tmp2;
                $tmp2   = false;
                $tmpGid = $question['question_gid'];
            }
            if (false === $tmp2) {
                $tmp2        = $question;
            }
           $tmp2['langs'][]  = $question;
            /**
             * Final element
             */
            if ($index == count($allQuestion) - 1) {
                $tmp[] = $tmp2;
            }
        }
        $allQuestion = $tmp;
//        echo '<pre>';print_r($allQuestion);die;

        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        
        
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allQuestion = $allQuestion;
        $this->view->questionMessage = $this->session->questionMessage;
        $this->session->questionMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_question');
        $this->view->allLangs = $allLangs;
    }
    
    public function newQuestionAction()
    {
        $objCat = new Models_ContentCategory();
        $objLang = new Models_Lang();
        $objQuestion = new Models_Question();
        
        $objAnswer = new Models_Answer();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_question', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        $data2 = $this->_getParam('data2', false);
        
//         echo "<pre>";print_r($data2);die;
        
        /**
         * Get all categories
         */
        $allCats = $objCat->buildTree($objCat->getAllCategories(1,array('sorting ASC')));
        
      
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('new_question', null, $lang['lang_id'])) {
                /**
                 * Clear data
                 */
//                 unset($data[$lang['lang_id']]);
                /**
                 * Disappear this language
                 */
//                 unset($allLangs[$index]);
            }
        }
        
        
        $errors = array();
        $objUnit = new Models_Unit();
        $all = $objUnit->getAll();
        $allUnit = $all->toArray();
        //tam
//        echo "<pre>";print_r($data2);die;
        if (false !== $data) {
            /**
             * Insert new question
             */
            $newQuestion = $data;
            $newQuestion['created_date'] = time();
           
         $newQuestion['update'] = time();
            
            $search = array(" ");
           
             $value = $data['level'];
             $objUnit = new Models_Unit();
             $add['name'] = $value;
             
             if($value){
                $flag = 0;
                $add['name'] = trim($value);
                
                $newQuestion['level'] = $objUnit -> getIdOrInsert($add['name']);
//                 echo "<pre>";print_r($newQuestion);die;
             }
             
            
            /**
             * Sorting
             */
            if (null == $newQuestion['sorting']) {
                unset($newQuestion['sorting']);
            }
            if (false == $this->checkPermission('new_question', null, '*')) {
                $newQuestion['genabled']          = 0;
                $newQuestion['sorting']           = 1;
            }
        
            /**
             * Slipt intro_text & full_text
             */
          
          //  try {
                /**
                 * Increase all current sortings
                 */
              
                
//               echo "<pre>";print_r($newQuestion);die;
                
                $pgid = $objQuestion->insert($newQuestion);
                // add answer
                foreach ($allLangs as $lang)
                {
                	$answer = $data2[$lang['lang_id']]['answer'];
                	$checkAnswer = explode(',', $data2[$lang['lang_id']]['checkAns']);
                	foreach ($answer as $index => $ans)
                	{
                		 
                		$newAnswer = array(
                				'answer_id' => "",
                				'question_gid' => $pgid,
                				'content' => $ans,
                				'is_true' => $checkAnswer[$index],
                				'lang_id' => $lang['lang_id'],
                				'created_date' => time()
                				 
                		);
                		$objAnswer->insert($newAnswer);
                	}
                }
                
                
                
                /**
                 * Message
                 */
                $this->session->questionMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Question is created successfully.')
                        );
                $this->_redirect('question/admin/manage-question');
           // } catch (Exception $e) {
             //   $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            //}
        } else {
            $data = array('sorting' => 1);
            $name = $this->_getParam('name', false);
            if(false == $name) {
                $data = array();
            } else {
                $data['title'] = $name;
            }
            $objUnit = new Models_Unit();
            $unit = @current($objUnit->find($data['unit'])->toArray());
            $data['unit'] = $unit['name'];
            
        }
        
        /**
         * Prepare for template
         */
        
         $this->view->allUnits = $allUnit;
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
//        echo "<pre>";print_r($data);die;
        $this->view->allUnits = $allUnit;
        
        $this->view->allCats = $allCats;
        $this->view->allLangs = $allLangs;
        $this->view->errors = $errors;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New Question'));
        $this->view->menu = array('question', 'newquestion');
        $this->view->fullPermisison = $this->checkPermission('new_question', null, '*'); 
    }


    
    
    
    

    
    public function editQuestionAction()
    {
        $objQuestion = new Models_Question();
        $objCat     = new Models_ContentCategory();
        $objLang    = new Models_Lang();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_question', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid     = $this->_getParam('gid', false);
        $lid    = $this->_getParam('lid', false); 
        if (false == $gid) {
            $this->_redirect('question/admin/manage-question');
        }
        /**
         * Check permission
         */
        if ((false == $lid && false == $this->checkPermission('edit_question', null, '*'))
        ||  (false != $lid && false == $this->checkPermission('edit_question', null, $lid))) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data   = $this->_getParam('data', false);
        $data2   = $this->_getParam('data2', false);
        $objUnit = new Models_Unit();
        $all = $objUnit->getAll();
        $allUnit = $all->toArray();
        /**
         * Get all categories
         */
        $allCats = $objCat->buildTree($objCat->getAllCategories(1,array('sorting ASC')));
        /**
         * Get all question languages
         */
        
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        $allQuestionLangs = $objQuestion->setAllLanguages(true)->getByColumns(array('question_gid=?' => $gid))->toArray();
// echo "<pre>";print_r($allQuestionLangs);die;
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $lang) {
            if (false == $this->checkPermission('edit_question', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
//                 unset($allLangs[$index]);
//                 unset($allQuestionLangs[$lang['lang_id']]);
//                 unset($data[$lang['lang_id']]);
            }
        }
        
        $errors = array();
//         echo "<pre>";print_r($allQuestionLangs);die;
        if (false !== $data) {
            /**
             * Insert new question
             */
            $newQuestion = $data;
            /**
             * Change format date
             */
           
             $newQuestion['update'] = time();
            
            $search = array(" ");
          
             $value = $data['level'];
             $add['name'] = $value;
             
             if($value){
                $flag = 0;
                $add['name'] = trim($value);
                
                $newQuestion['level'] = $objUnit -> getIdOrInsert($add['name']);
             }
            
             
            /**
             * Sorting
             */
            if (null == $newQuestion['sorting']) {
                unset($newQuestion['sorting']);
            }
           
        
            /**
             * Slipt intro_text & full_text
             */
            foreach ($allLangs as $index => $lang) {
//                  list($newQuestion[$lang['lang_id']]['intro_text'], $newQuestion[$lang['lang_id']]['full_text'])= Nine_Function::splitTextWithReadmore($newQuestion[$lang['lang_id']]['full_text']);
            }
            /**
             * Remove empty images
             */
           
            try {
                /**                
                 * Update
                 */
                
            	//tam
//             	echo '<pre>';print_r($newQuestion);die;
                $objQuestion->update($newQuestion, array('question_gid=?' => $gid));
                $objAnswer = new Models_Answer();
                $allAnswers = $objAnswer->getAllAnserById($gid);
//                 echo "<pre>";print_r($allAnswers);die;
                foreach ($allAnswers as $index => $ans)
                {
                	$objAnswer->delete(array('answer_id=?' => $ans['answer_id']));
                }
                foreach ($allLangs as $lang)
                {
                	$answer = $data2[$lang['lang_id']]['answer'];
                	$checkAnswer = explode(',', $data2[$lang['lang_id']]['checkAns']);
                	foreach ($answer as $index2 => $ans)
                	{
                		 
                		$newAnswer = array(
                				'answer_id' => "",
                				'question_gid' => $gid,
                				'content' => $ans,
                				'is_true' => $checkAnswer[$index2],
                				'lang_id' => $lang['lang_id'],
                				'created_date' => time()
                				 
                		);
//                 		echo "<pre>";print_r($newAnswer);die;
                		$objAnswer->insert($newAnswer);
                	}
                }
                
                	
                	
                /**
                 * Message
                 */
                $this->session->questionMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Question is updated successfully.')
                        );
                
                $this->_redirect('question/admin/manage-question');
            } catch (Exception $e) {
//                 $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            /**
             * Get old data
             */
            $data = $allQuestionLangs;
//             echo "<pre>";print_r($allQuestionLangs);die;
            /**
             * Get all lang contents
             */
            $data = array();
            foreach ($allQuestionLangs as $key=>$content) {
            	/**
            	 * Rebuild readmore DIV
            	 */
            	$content['full_text'] = Nine_Function::combineTextWithReadmore($content['intro_text'], $content['full_text']);
            	
            	$objAnswer = new Models_Answer();
            	$allAnswers = $objAnswer->getAnserById($content['question_gid'],$content['lang_id'] );
            	//echo '<pre>';print_r($allAnswers);die;
            	$lastAns = end($allAnswers);
            	$data[$content['lang_id']] = $content;
            	$data[$content['lang_id']]['last_ans'] = $lastAns;
            	$data[$content['lang_id']]['answer'] = $allAnswers;
            	$unit = @current($objUnit->find($content['level'])->toArray());
            	$data['level'] = $unit['name'];
            	$data['sorting'] = $content['sorting'];
            	$data['genabled'] = $content['genabled'];
            	$data['type'] = $content['type'];
            }
//             echo "<pre>";print_r($data);die;
            /**
             * Add deleteable field
             */
//             if (null != @$data['content_category_gid']) {
//             	$cat = @reset($objCat->getByColumns(array('content_category_gid' => $data['content_category_gid']))->toArray());
//             	$data['content_deleteable'] = @$cat['content_deleteable'];
//             }
            
            
            
//             $objAnswer = new Models_Answer();
//             $allAnswers = $objAnswer->getAnserById($data['question_gid']);
//             $lastAns = end($allAnswers);
//             $this->view->allAnswer = $allAnswers;
//             $this->view->lastAns = $lastAns;
            
            
            if (false == $data) {
                $this->session->questionMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate("Question doesn't exist.")
                                           );
                $this->_redirect('question/admin/manage-question');
            }
            /**
             * Change date
             */
           
            
           
            /**
             * Get all lang questions
             */
//             foreach ($allQuestionLangs as $question) {
//                 $data[$question['lang_id']] = $question;
//             }
        }
//        echo "<pre>";print_r($data);die;
        /**
         * Prepare for template
         */
        $this->view->allUnits = $allUnit;
        $this->view->allCats = $allCats;
        $this->view->allLangs = $allLangs;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->lid = $lid;
        $this->view->errors = $errors;
        $this->view->data = $data;
        
        $this->view->headTitle(Nine_Language::translate('Edit Question'));
        $this->view->menu = array('question','');
        $this->view->fullPermisison = $this->checkPermission('edit_question', null, '*');
    }
    
    
    
    
    
    
     public function addInputAction()
    {
         $value = $this->_getParam('value', false);
         $objUnit = new Models_Unit();
         $data['name'] = $value;
         if($data['name']){
            $id = $objUnit->insert($data);
            $this->setLayout('default');
            $this->view->id = $id;
         }
         
    }
    
    
    
   
   
public function editInputAction()
    {
       
        
        $id     = $this->_getParam('id', false);     
        
        if (false == $id) {
            $this->_redirect('question/admin/manage-question');
        }
        /**
         * Check permission
         */
        $objInput = new Models_Input();
//        $input = $objInput->getInputById($id);
        if (false == $this->checkPermission('edit_input', null, '*'))
        {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        
        $inputPost = $this->_getParam('input', false);
        $objQuestion = new Models_Question();
        $idInput =  $inputPost['num'];
        $input = $inputPost[$idInput];
        

        $errors = array();
       
        if (false !== $input) {
            
            $newInput = $input;
            if (null == $newInput['created_date']) {
                unset($newInput['created_date']);
            } else {
                $tmp = explode('/', $newInput['created_date']);
                $newInput['created_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            	
             try {
                /**                
                 * Update
                 */
                $oldInput = $objInput->getInputById($idInput);
                $objInput->update($newInput, array('input_id=?' => $idInput));
                $question = $objQuestion->getQuestionById($oldInput['question_id']);
//                echo "<pre>";print_r($question);die;
                if($newInput['soluong']){
                    $question['store'] = $question['store'] - $oldInput['soluong'] + $newInput['soluong'];
                    $objQuestion->update($question, array('question_id=?'=> $question['question_id']));
                }
                
                /**
                 * Message
                 */
                $this->session->questionMessage =  array(
                           'success' => true,
                           'message' => 'Thông tin nhập hàng cập nhật thành công.'
                        );
                
                $this->_redirect('question/admin/select/id/'.$oldInput['question_id']);
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Không thể cập nhật thông tin nhập hàng'));
            }
            
            	
            	
                    
        }
        /*
         * end edit input
         */
    }
    

    
    public function searchQuestionAction()
    {
        $objQuestion = new Models_Question();
        $group = Nine_Registry::getLoggedInGroupId();
        $this->view->group = $group;
        /**
         * Check permission
         */
        if (false == $this->checkPermission('search_question', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
//        echo "<pre>";print_r($_POST);die;
        $this->view->headTitle('Thống kê giao dịch');
        $this->view->menu = array('question', 'searchquestion');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        $objQuestion = new Models_Question();
        $errors = array();
        
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->questionDisplayNum;
        } else {
            $this->session->questionDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->questionCondition;
        } else {
            $this->session->questionCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        
//        $allQuestion = $objQuestion->getAllQuestions($condition, array('question_id DESC','update DESC'),
//                                                   $numRowPerPage,
//                                                   ($currentPage - 1) * $numRowPerPage
//                                                  );
        /**
         * Count all questions
         */
        $count = count($objQuestion->getAllQuestions($condition));

        /**
         * Format
         */
//        foreach ($allQuestion as $index=> &$question) {
//            /**
//             * Change date
//             */
//            if (0 != $question['created_date']) {
//                $question['created_date'] = date($config['dateFormat'], $question['created_date']);
//            } else {
//                $question['created_date'] = '';
//            }
//            
//            if($question['unit']){
//                $objUnit = new Models_Unit();
//                $con['unit_id'] = $question['unit'];
//                $unit =     $objUnit->getUnitById($question['unit']);
//                
////                echo "<pre>";print_r($unit);die;
//                $question['unit'] = $unit['name'];
////              echo "<pre>";print_r($question);die;
//            }
//        }
//        unset($question);
        
        $objInput = new Models_Input();
        
        $allInput = $objInput->getAllInputs($condition, array('created_date DESC'));
//        echo "<pre>";print_r($allInput);die;
        $objUnit = new Models_Unit();
        
        $objSale = new Models_Sale();
        $allSale = $objSale->getAllSales($condition,array('created_date DESC'));
//        echo "<pre>";print_r($allSale);die;
        foreach ($allInput as &$item) {
            if (0 != $item['created_date']) {
                $item['created_date'] = date($config['dateFormat'], $item['created_date']);
            } else {
                $item['created_date'] = '';
            }
            $question =  $objQuestion->getQuestionById($item['question_id']);
            $item['question_name'] = $question['title'];
            $item['provider'] = $question['provider'];
            $con['unit_id'] = $question['unit'];
            $unit =     $objUnit->getUnitById($question['unit']);
            $item['unit'] =  $unit['name'];
        }
        unset($item);
//        echo "<pre>";print_r($allInput);die;
        
        foreach ($allSale as &$sale) {
            if (0 != $sale['created_date']) {
                $sale['created_date'] = date($config['dateFormat'], $sale['created_date']);
            } else {
                $sale['created_date'] = '';
            }
            $question =  $objQuestion->getQuestionById($sale['question_id']);
//            echo "<pre>";print_r($question);die;
            $sale['question_name'] = $question['title'];
            $sale['provider'] = $question['provider'];
            $con['unit_id'] = $question['unit'];
            $unit =     $objUnit->getUnitById($question['unit']);
            $sale['unit'] =  $unit['name'];
            
        }
        unset($sale);
//        echo "<pre>";print_r($allSale);die;
        $total = 0;
        $totalGiaBan = 0;
        foreach ($allInput as $item ) {
            $total = $total + ($item['input_price'] * $item['soluong']);
            $totalGiaBan = $totalGiaBan + ($item['lsale_price'] * $item['soluong']);
        }
        $totalInSale = 0;
        $totalOuSale = 0;
        foreach ($allSale as $item1 ) {
            $totalInSale = $totalInSale + ($item1['sale_price'] * $item1['soluong']);
            $totalOuSale = $totalOuSale + ($item1['lsale_price'] * $item1['soluong']);
        }
        
        $this->view->allInputs = $allInput;
        $this->view->allSales = $allSale;
        
        $this->view->total = number_format($total,0,',', ' ');
        $this->view->totalGiaBan = number_format($totalGiaBan,0,',', ' ');
        $this->view->totalInSale = number_format($totalInSale,0,',', ' ');
        $this->view->totalOuSale = number_format($totalOuSale,0,',', ' ');
        
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        
        $this->view->date = $date;
        
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->questionMessage = $this->session->questionMessage;
        $this->session->questionMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_question');
    }
    
    

    public function enableQuestionAction()
    {
        $objQuestion = new Models_Question();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('question/admin/manage-question');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_question', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objQuestion->update(array('genabled' => 1), array('question_gid=?' => $gid));
                }
                $this->session->questionMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Question is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->questionMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this question. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_question', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objQuestion->update(array('enabled' => 1), array('question_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->questionMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Question is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->questionMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this question. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('question/admin/manage-question');
    }

    
    public function disableQuestionAction()
    {
        $objQuestion = new Models_Question();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('question/admin/manage-question');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_question', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objQuestion->update(array('genabled' => 0), array('question_gid=?' => $gid));
                }
                $this->session->questionMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Question is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->questionMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this question. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_question', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objQuestion->update(array('enabled' => 0), array('question_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->questionMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Question is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->questionMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this question. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('question/admin/manage-question');
    }
    
    public function deleteQuestionAction()
    {
        $objQuestion = new Models_Question();
        $objCat = new Models_ContentCategory();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_question')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid = $this->_getParam('gid', false);
        
        if (false == $gid) {
            $this->_redirect('question/admin/manage-question');
        }
        
        $gids = explode('_', trim($gid, '_'));
        
        try {
            foreach ($gids as $gid) {
            	$question = @reset($objQuestion->getByColumns(array('question_gid=?'=>$gid))->toArray());
            	$cat = @reset($objCat->getByColumns(array('content_category_gid=?'=>$question['content_category_gid']))->toArray());
            	if ( 0 == $cat['content_deleteable']){
            		$this->session->questionMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete question ('. $gid .'). Please try again')
                                           );
                    $this->_redirect('content/admin/manage-question');
            	}
            	else {
            		 $objQuestion->delete(array('question_gid=?' => $gid));
            	}
            }
            $this->session->questionMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Question is deleted successfully')
                                           );
        } catch (Exception $e) {
            $this->session->questionMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this question. Please try again')
                                           );
        }
        $this->_redirect('question/admin/manage-question');
    }
    
    
    /**************************************************************************************************
     *                                         CATEGORY's FUNCTIONS
     **************************************************************************************************/
    
    
    
    

    
    

    

    
    
    
    
}